package top.hmtools.configClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * 本工程程序总入口
 * 
 * @author Hybo
 * 
 */
@SpringBootApplication(exclude = MongoAutoConfiguration.class)
@EnableDiscoveryClient
public class ConfigClientApplication {
	protected static final Logger logger = LoggerFactory.getLogger(ConfigClientApplication.class);
	
	private static String appName = "spring config client";
	
	public static void main(String[] args) {
		// 初始化 spring boot
		ConfigurableApplicationContext applicationContext = SpringApplication.run(ConfigClientApplication.class, args);
		if(applicationContext != null){
			logger.info(appName+"已经成功启动！~applicationContext："+applicationContext);
		}
		

		// 优雅关闭本进程：
		InputStream in = System.in;
		InputStreamReader isr = new InputStreamReader(in);
		char[] tmp = new char[1024];
		int end = 0;
		try {
			while((end=isr.read(tmp))>-1){
				String cmdStr = new String(tmp,0,end);
				if("shutdown".equals(cmdStr.trim().toLowerCase())){
					logger.info("接收到关闭程序指令，尝试关闭进程。。。");
					int exitCode = SpringApplication.exit(applicationContext, new ExitCodeGenerator() {
						@Override
						public int getExitCode() {
							return 0;
						}
					});
					if(exitCode==0){
						logger.info("成功正常关闭进程。");
					}else{
						logger.info("关闭进程发生异常，错误码："+exitCode);
					}
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		};

	}

}
